import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { LogsService } from '../../logs/logs.service';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  constructor(private readonly logsService: LogsService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    const { method, path, user, body, query } = request;

    return next.handle().pipe(
      tap(async (result) => {
        if (user) {
          await this.logsService.createLog({
            userId: user.id,
            username: user.username,
            operation: `${method} ${path}`,
            method,
            path,
            params: { ...body, ...query },
            result,
          });
        }
      }),
    );
  }
} 